/**
 * 网络请求的工具类
 */
import React, {Component} from 'react';

import {
    ToastAndroid,
    NativeModules,
} from 'react-native';
import Toast from "teaset/components/Toast/Toast";
import {version} from "./Config";
import Api from "./Api";
import {Actions} from "react-native-router-flux";
const TAG = 'wangyu';
export default class NetUtils extends Component {

    constructor(props) {
        super(props);
    }

    /**
     * 普通的get请求
     * @param {*} url 地址
     * @param {*} params  参数
     * @param {*} resultCallback  成功后的回调
     * @param {} completeCallback 结束回调  不管成功还是失败  可不穿
     */
    static get(url, params,resultCallback,completeCallback) {
        let newParams = this.getNewParams(params);
        console.log(TAG,'get:'+url + "?" + newParams);
        NativeModules.MyNativeMoudle.encrypt(newParams, (apiKey, sign) => {
            fetch(url + "?" + newParams, {
                headers: {
                    'apiKey': apiKey,
                    'sign': sign,
                }
            })
                .then((response) => response.json())
                .then((json) => {
                console.log(TAG,json);
                    if(completeCallback){
                        completeCallback(json);
                    }
                    if (json.code === -99) {
                        //弹出登录页面
                        Actions.LoginPage();
                    }else {
                        resultCallback(json);
                    }
                }).catch(error => {
                    console.log(TAG,error);
                if(completeCallback){
                    completeCallback(error);}
                Toast.message('网络请求失败,请检查网络配置' + error.toString())
            });
        });

    };


    /**
     * post key-value 形式 hader为'Content-Type': 'application/x-www-form-urlencoded'
     * @param {*} url
     * @param {*} params
     * @param {*} callback
     * @param   dontCheck  为true的时候不检查-99,不传默认检查
     */
    static post(url, params, callback,completeCallback,dontCheck){
        //添加公共参数
        let newParams = this.getNewParams(params);//接口自身的规范，可以忽略
        console.log(TAG,'post:'+url + "?" + newParams);
        NativeModules.MyNativeMoudle.encrypt(newParams, (apiKey, sign) => {
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',//key-value形式
                    'apiKey': apiKey,
                    'sign':sign
                },
                body: newParams
            })
                .then((response) => response.json())
                .then((json) => {
                    console.log(TAG,json);
                    if(completeCallback){
                        completeCallback(json);
                    }
                    if (!dontCheck&&json.code === -99) {
                        //弹出登录页面
                        Actions.LoginPage();
                    }else {
                        callback(json);
                    }
                }).catch(error => {
                console.log(TAG,error);
                if(completeCallback){
                    completeCallback(error);
                }
                Toast.message('网络请求失败,请检查网络配置'+error.toString())
            });
        });
    }

    /**
     * post json形式  header为'Content-Type': 'application/json'
     * @param {*} url
     * @param {*} service
     * @param {*} jsonObj
     * @param {*} callback
     */
    static postJson(url, jsonObj, callback) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify(jsonObj),//json对象转换为string
        })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                }
            })
            .then((json) => {
                if (json.resultCode === 1) {
                    callback(json);
                } else {
                    ToastAndroid.show(json.resultDesc, ToastAndroid.SHORT);
                }
            }).catch(error => {
            Toast.message('网络请求失败,请检查网络配置')
        });
    };

    /**
     * 设置公共参数
     * @param {*} arams 参数 key-value形式的字符串
     * @return 新的参数
     */
    static getNewParams(params) {
        if (params === null) {
            params = "accessPort=2&version=" + version;
        } else {
            params = params + "&accessPort=2&version=" + version;
        }
        if (Api.isLogin) {
            params = params + "&userId=" + Api.userInfo.userId + "&token=" + encodeURI(Api.userInfo.token);
        }
        return params;
    };
}
